module(..., package.seeall)
--- 模块功能：MQTT客户端数据接收处理
-- @author openLuat
-- @module mqtt.mqttInMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
require "getLbsLoc"
require "nvm"
require "mqttHostOutMsg"
require "doorLocStatFeedback"
require "utilsACS"
require "displayLogic"
nvm.init("config.lua", true)
QuakeCancelFlag = false
local clientNo, hostNo = nvm.get("ClientNo"), nvm.get("HostNo")
local quakeRevCount, quakeRevCountPre = 0, 1
-- 设备绑定-设备身份判别
local function containClientsOrNot(equipment_clientNos)
    local clientNoList = string.split(equipment_clientNos, ",")
    local containResult = false
    log.info("#clientNoList", #clientNoList)
    for i = 1, #clientNoList do
        log.info("clientNoList", clientNoList[i], "clientNo", clientNo)
        if clientNoList[i] == clientNo then containResult = true end
    end
    return containResult
end
local function quakeCancelJudge()
    while true do
        log.info("quakeRevCountPre:",quakeRevCountPre,"quakeRevCount:",quakeRevCount)
        if quakeRevCountPre - quakeRevCount>3 then
            quakeRevCount = 0
            quakeRevCountPre = 1
            QuakeCancelFlag = true
            break
        end
        sys.wait(1000)
        quakeRevCountPre = quakeRevCountPre + 1
    end
end
-- 获取地震预警相关信息
local function getMsgAboutQuake(quakeInfo)
    local quakeInfoList, redReturn, greeReturn, blueReturn, countDownReturn,
          intensityReturn, hzReturn, voicePlay = {}, "", "", "", "", "", "", ""
    quakeInfoList = string.split(quakeInfo, ",")
    redReturn = quakeInfoList[3]
    greeReturn = quakeInfoList[4]
    blueReturn = quakeInfoList[5]
    countDownReturn = quakeInfoList[6]
    intensityReturn = quakeInfoList[8]
    hzReturn = quakeInfoList[12]
    voicePlay = quakeInfoList[9]
    return redReturn, greeReturn, blueReturn, countDownReturn, intensityReturn,
           hzReturn, voicePlay
end
--- MQTT客户端数据接收处理
-- @param mqttClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttInMsg.proc(mqttClient)
function HostInsertProc(mqttClient)
    local result, data, receiveMsg
    while true do
        result, data = mqttClient:receive(60000, "APP_SOCKET_SEND_DATA")
        log.info("mqttHost:", result)
        local clientNos, hostNoGet, content
        -- 接收到数据
        if result then
            log.info("data topic", data.topic)
            log.info("mqttInMsg.proc", data.topic, data.payload)
            receiveMsg = data.payload
            local tjsondata, resultMqtt, errinfo = json.decode(receiveMsg)
            log.info("resultMqtt:", resultMqtt, "errinfo:", errinfo)
            local action, sendMsg, topic, open
            if data.topic == "acs/" .. clientNo then
                if resultMqtt and type(tjsondata) == "table" then
                    action = tjsondata["action"]
                    if action == "get" then
                        topic = "acs/" .. hostNo
                        log.info("topicGet:", topic)
                        sendMsg = "{" .. "\"action\":\"info\",\"slaveNo\":\"" ..
                                      clientNo .. "\",\"status\":\"" ..
                                      tostring(
                                          doorLocStatFeedback.GetGpio24Fnc()) ..
                                      "\"}"
                        mqttHostOutMsg.InsertHostMsg(topic, sendMsg, 0)
                    elseif action == "door" then
                        open = tjsondata["open"]
                        if "0" == open then
                            -- 开门
                            log.info("开门")
                            utilsACS.OpenDoorAction()
                        end
                    elseif action == "alarm" then -- 紧急报警逻辑
                        if not utilsACS.QuakeInterruptFlag then
                            utilsACS.EmergencyAlarmLogic()
                        end
                    elseif action == "alarmCancel" then -- 紧急报警取消
                        utilsACS.EmergencyAlarmCancel()
                    elseif action == "quake" then -- 地震预警逻辑
                        log.info("quakeRevCount:",quakeRevCount,"QuakeCancelFlag:",QuakeCancelFlag)
                        quakeRevCount = quakeRevCount + 1
                        if quakeRevCount == 1 then
                            QuakeCancelFlag = false
                            sys.taskInit(quakeCancelJudge)
                        end
                        local red, gree, blue, countDown, intensity, hz, voice
                        content = tjsondata["content"]
                        -- 截取所需内容
                        red, gree, blue, countDown, intensity, hz, voice =
                            getMsgAboutQuake(content)
                        utilsACS.QuakeAction(red, gree, blue, countDown,
                                             intensity, hz, voice)
                    elseif "quakeCancel" then
                    elseif action == "config" then
                    end
                end
            elseif data.topic == "acs/bind" then
                if resultMqtt and type(tjsondata) == "table" then
                    clientNos = tjsondata["clientNos"]
                    log.info("clientNos", clientNos, "clientNo:", clientNo)
                    if containClientsOrNot(clientNos) then
                        log.info("TEST1")
                        hostNoGet = tjsondata["hostNo"]
                        if hostNoGet ~= nill and hostNoGet ~= "" and hostNoGet ~=
                            hostNo then
                            log.info("TEST2")
                            nvm.set("HostNo", hostNoGet)
                            sys.restart("主机绑定成功，设备重启！")
                        end
                    end
                end
            end
        else
            break
        end
    end
    return result or data == "timeout" or data == "APP_SOCKET_SEND_DATA"
end
